﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using DevExpress.XtraGrid.Views.Grid;
using QuanLyTiemThuocTay.cls;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using DevExpress.XtraGrid.Localization;
using QuanLyTiemThuocTay.Report;

namespace QuanLyTiemThuocTay.GUI
{
    public partial class frmPhieuNhap : DevExpress.XtraEditors.XtraForm
    {
        public frmPhieuNhap()
        {
            InitializeComponent();
            GridLocalizer.Active = new GridLocalizer();
            btIn.Enabled = false;
        }

        QLTTDataContext db = new QLTTDataContext();
        private int indexdongmoi;
        private int indexdongcu;
        List<CHITIETNHAPDVT> ctns;
        private NHACUNGCAP nhacungcap;
        private void frmPhieuNhap_Load(object sender, EventArgs e)
        {
            btLuu.Enabled = true;
            btXoa.Enabled = btSua.Enabled = false;
            leTenThuoc.DataSource = seThuoc.Properties.DataSource = new BindingList<THUOC>(db.THUOCs.ToList());
            leDVT.DataSource = new BindingList<DVTINH>(db.DVTINHs.ToList());
            leGiaThuoc.DataSource = new BindingList<GIATHUOC>(db.GIATHUOCs.ToList());
            cbbNhaCungCap.Properties.DataSource = new BindingList<NHACUNGCAP>(db.NHACUNGCAPs.ToList());
            dtNgayLapPhieu.EditValue = DateTime.Now;
            ctns = new List<CHITIETNHAPDVT>();
            tbSoPhieuNhap.Text = TaoSoPhieu();
        }

        private string TaoSoPhieu()
        {
            string str = "";
            var ob = db.HDNHAPs.ToList();
            if (ob.Count > 0)
            {
                int code = Int32.Parse(ob.Last().SoHDNhap.Substring(2, ob.Last().SoHDNhap.Length - 2));
                HDNHAP hd = null;
                do
                {
                    code++;
                    if (code < 10)
                        str = "PN0000" + code;
                    else if (code < 100)
                        str = "PN000" + code;
                    else if (code < 1000)
                        str = "PN00" + code;
                    else if (code < 10000)
                        str = "PN0" + code;
                    else str = "PN" + code;
                    hd = db.HDNHAPs.SingleOrDefault(x => x.SoHDNhap == str);
                } while (hd != null);
                return str;
            }
            else
                return "PN00001";
        }

        private void btMoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            tbSoPhieuNhap.Text = TaoSoPhieu();
            btSua.Enabled = btXoa.Enabled = btIn.Enabled = false;
            btLuu.Enabled = true;
            cbbNhaCungCap.ShowPopup();
        }

        private void leKhachHang_AddNewValue(object sender, DevExpress.XtraEditors.Controls.AddNewValueEventArgs e)
        {

        }

        private void btDong_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }

        private void btMo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            btLuu.Enabled = false;
            btSua.Enabled = btXoa.Enabled = btIn.Enabled = true;
            clsHam.returnvalueinputbox = "";
            frmInput ip = new frmInput("Nhập giá trị", "Nhập số phiếu cần mở:");
            ip.ShowDialog();
            if (clsHam.returnvalueinputbox.Trim().Length > 0)
            {
                HDNHAP hdn = db.HDNHAPs.SingleOrDefault(x => x.SoHDNhap == clsHam.returnvalueinputbox);
                if (hdn != null)
                {
                    tbSoPhieuNhap.Text = hdn.SoHDNhap;
                    tbDaiDien.Text = hdn.DaiDien;
                    var ncc = db.NHACUNGCAPs.SingleOrDefault(x => x.TenNhaCC == hdn.NhapTuDonVi);
                    if (ncc != null)
                        cbbNhaCungCap.EditValue = ncc.MaNhaCC;
                    else
                    {
                        cbbNhaCungCap.Text = hdn.NhapTuDonVi;
                        tbDiaChi.Text = "Đã xóa nhà cung cấp này ra khỏi hệ thống";
                    }
                    var lctn = db.CHITIETNHAPs.Where(x => x.SoHDNhap == hdn.SoHDNhap).ToList();
                    List<CHITIETNHAPDVT> lctndvt = new List<CHITIETNHAPDVT>();
                    foreach (var item in lctn)
                    {
                        CHITIETNHAPDVT te = new CHITIETNHAPDVT();
                        te.MaChiTiet = item.MaChiTiet;
                        te.MaDonGia = item.MaDonGia;
                        te.MaDVTinh = (int)db.THUOCs.Single(x => x.MaThuoc == item.MaThuoc).MaDVTinh;
                        te.MaThuoc = item.MaThuoc;
                        te.SoHDNhap = hdn.SoHDNhap;
                        te.SoLuong = item.SoLuong;
                        lctndvt.Add(te);
                    }
                    gc.DataSource = null;
                    gc.RefreshDataSource();
                    gc.DataSource = lctndvt;
                    gc.RefreshDataSource();
                }
                else
                    clsHam.HienThi(Text, "Không có phiếu nhập nào phù hợp với số phiếu này: " + clsHam.returnvalueinputbox);
            }
        }

        private void gv_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            GridView view = sender as GridView;
            view.SetRowCellValue(e.RowHandle, view.Columns["SoHDNhap"], tbSoPhieuNhap.Text);
            // view.SetRowCellValue(e.RowHandle, view.Columns["SoLuong"], 1);
        }

        private void gv_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
            (sender as GridView).ShowEditor();
        }

        private void gv_ShowingEditor(object sender, CancelEventArgs e)
        {
            //GridView view = sender as GridView;
            //GridColumn col = sender as GridColumn;
            //if (gv.FocusedColumn.Name != "colThanhTien")
            //    if (view.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            //    {
            //        e.Cancel = false;
            //    }
            //    else
            //    {
            //        e.Cancel = true;
            //    }
        }

        private void gv_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            indexdongcu = e.PrevFocusedRowHandle;
            indexdongmoi = e.FocusedRowHandle;
            gv.SetRowCellValue(indexdongmoi, gv.Columns["SoHDNhap"], tbSoPhieuNhap.Text);
        }

        private void btXoaRow_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            gv.DeleteRow(gv.FocusedRowHandle);
        }

        int ThanhTien(string soluong, string dongia)
        {
            int sl = 0;
            int dg = 0;
            if (Int32.TryParse(soluong, out sl) && Int32.TryParse(dongia, out dg))
                return sl * dg;
            else
                return 0;
        }

        private void seThuoc_EditValueChanged(object sender, EventArgs e)
        {
            if (tbSoPhieuNhap.Text.Trim().Length > 0)
            {
                try
                {
                    List<GIATHUOC> giathuocs = db.GIATHUOCs.Where(x => x.MaThuoc == seThuoc.EditValue.ToString()).ToList();
                    if (giathuocs.Count > 0)
                    {
                        CHITIETNHAPDVT ctn = new CHITIETNHAPDVT();
                        ctn.MaDonGia = giathuocs.Last().MaDonGia;
                        ctn.MaThuoc = seThuoc.EditValue.ToString();
                        ctn.MaDVTinh = (int)db.THUOCs.Single(x => x.MaThuoc == seThuoc.EditValue.ToString()).MaDVTinh;
                        ctn.SoHDNhap = tbSoPhieuNhap.Text;
                        ctn.SoLuong = 1;
                        ctn.ThanhTien = giathuocs.Last().GiaNhap;
                        ctns.Add(ctn);
                        gc.DataSource = null;
                        gc.RefreshDataSource();
                        gc.DataSource = ctns;
                        gc.RefreshDataSource();
                    }
                    else
                        clsHam.HienThi(Text, "Chưa có đơn giá nhập cho thuốc/thiết bị này");
                }
                catch { }
            }
            else
                clsHam.HienThi(Text, "Chưa có số Hóa đơn nhập");
        }

        private void gv_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            try
            {
                if (e.Column.FieldName == "ThanhTien" && e.IsGetData)
                {
                    var a = gv.GetRow(e.ListSourceRowIndex) as CHITIETNHAPDVT;
                    var b = db.GIATHUOCs.SingleOrDefault(x => x.MaDonGia == a.MaDonGia).GiaNhap;
                    e.Value = a.SoLuong * b;
                }
            }
            catch { }
        }

        private void cbbNhaCungCap_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                string manhacungcap = cbbNhaCungCap.EditValue.ToString();
                nhacungcap = db.NHACUNGCAPs.SingleOrDefault(x => x.MaNhaCC == manhacungcap);
                if (nhacungcap != null)
                    tbDiaChi.Text = nhacungcap.DiaChi;
                else
                    tbDiaChi.Text = "";
                tbDaiDien.Focus();
            }
            catch { }
        }

        private void btLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string daidien = tbDaiDien.Text.Trim();
            tbDaiDien.Text = daidien;
            dxValid.SetValidationRule(tbDaiDien, clsHam.ValidIsNotBlank("Chưa nhập tên người đại diện"));
            dxValid.SetValidationRule(cbbNhaCungCap, clsHam.ValidIsNotBlank("Chưa chọn nhà cung cấp"));
            if (gv.RowCount == 0)
                clsHam.HienThi(Text, "Chưa có danh sách thuốc thiết bị sẽ nhập");
            else if (dxValid.Validate())
            {
                HDNHAP hdn = new HDNHAP();
                hdn.SoHDNhap = tbSoPhieuNhap.Text;
                hdn.GhiChu = tbGhiChu.Text;
                hdn.DaiDien = tbDaiDien.Text;
                hdn.MaNguoiDung = 2;
                hdn.NgayNhap = DateTime.Parse(dtNgayLapPhieu.EditValue.ToString());
                hdn.NhapTuDonVi = cbbNhaCungCap.Text;
                db.HDNHAPs.InsertOnSubmit(hdn);
                List<CHITIETNHAP> lctn = new List<CHITIETNHAP>();
                for (int i = 0; i < gv.RowCount; i++)
                {
                    var temp = gv.GetRow(i) as CHITIETNHAPDVT;
                    CHITIETNHAP ctn = new CHITIETNHAP();
                    ctn.MaDonGia = temp.MaDonGia;
                    ctn.MaThuoc = temp.MaThuoc;
                    ctn.SoHDNhap = hdn.SoHDNhap;
                    ctn.SoLuong = temp.SoLuong;
                    lctn.Add(ctn);
                }
                if (lctn.Count > 0)
                    db.CHITIETNHAPs.InsertAllOnSubmit(lctn);
                db.SubmitChanges();
                btLuu.Enabled = false;
                btIn.Enabled = true;
            }
        }

        private void btXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show("Chắc chắc xóa phiếu nhập " + tbSoPhieuNhap.Text, "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                var hdn = db.HDNHAPs.SingleOrDefault(x => x.SoHDNhap == tbSoPhieuNhap.Text);
                if (hdn != null)
                {
                    db.HDNHAPs.DeleteOnSubmit(hdn);
                    db.SubmitChanges();
                }
                else
                    clsHam.HienThi(Text, "Không tồn tại phiếu nhập này trong hệ thống");
            }
        }

        private void btSua_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string daidien = tbDaiDien.Text.Trim();
            tbDaiDien.Text = daidien;
            dxValid.SetValidationRule(tbDaiDien, clsHam.ValidIsNotBlank("Chưa nhập tên người đại diện"));
            dxValid.SetValidationRule(cbbNhaCungCap, clsHam.ValidIsNotBlank("Chưa chọn nhà cung cấp"));
            if (gv.RowCount == 0)
                clsHam.HienThi(Text, "Chưa có danh sách thuốc thiết bị sẽ nhập");
            else if (dxValid.Validate())
            {
                HDNHAP hdn = db.HDNHAPs.SingleOrDefault(x => x.SoHDNhap == tbSoPhieuNhap.Text);
                if (hdn != null)
                {
                    hdn.NhapTuDonVi = cbbNhaCungCap.Text;
                    hdn.GhiChu = tbGhiChu.Text;
                    hdn.DaiDien = tbDaiDien.Text;
                    List<CHITIETNHAP> lctn = db.CHITIETNHAPs.Where(x => x.SoHDNhap == tbSoPhieuNhap.Text).ToList();
                    db.CHITIETNHAPs.DeleteAllOnSubmit(lctn);
                    db.SubmitChanges();
                    lctn = new List<CHITIETNHAP>();
                    for (int i = 0; i < gv.RowCount; i++)
                    {
                        var temp = gv.GetRow(i) as CHITIETNHAPDVT;
                        CHITIETNHAP ctn = new CHITIETNHAP();
                        ctn.MaDonGia = temp.MaDonGia;
                        ctn.MaThuoc = temp.MaThuoc;
                        ctn.SoHDNhap = hdn.SoHDNhap;
                        ctn.SoLuong = temp.SoLuong;
                        lctn.Add(ctn);
                    }
                    if (lctn.Count > 0)
                        db.CHITIETNHAPs.InsertAllOnSubmit(lctn);
                    db.SubmitChanges();
                }
            }
        }

        private void frmPhieuNhap_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case (Keys.F3):
                    seThuoc.ShowPopup();
                    break;
                case (Keys.F2):
                    cbbNhaCungCap.ShowPopup();
                    break;

            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void btNapLai_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (db.HDNHAPs.Where(x=>x.SoHDNhap==tbSoPhieuNhap.Text).ToList().Count>0)
            {
                
            }
        }

        private void btIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            new rptPhieuNhap(tbSoPhieuNhap.Text).ShowPreview();
        }
    }
}